﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Infinity.API.Core
{
	public class CodeRunManager
	{
		private readonly List<CodeAction> Codes = new List<CodeAction>();

		private static CodeRunManager m_Instance;

		public static CodeRunManager Instance
		{
			get
			{
				if (m_Instance == null)
					m_Instance = new CodeRunManager();
				return m_Instance;
			}
		}

		public CodeRunManager AddCommand(Action action)
		{
			Codes.Add(new CommandCodeAction(action));
			return this;
		}

		public CodeRunManager AddSequence(params Action[] actions)
		{
			Codes.Add(
				new SequenceCodeAction(
					actions.Select(action => new CommandCodeAction(action))
						   .ToArray<CodeAction>()));
			return this;
		}

		public CodeRunManager AddCondition(Func<bool> condition, Action action)
		{
			Codes.Add(new ConditionCodeAction(condition, new CommandCodeAction(action)));
			return this;
		}

		public CodeRunManager AddIfCondition(Func<bool> condition, Action ifAction, Action elseAction)
		{
			return AddCondition(condition, ifAction).AddCondition(() => !condition(), elseAction);
		}

		public CodeRunManager AddWhileLoop(Func<bool> condition, Action action)
		{
			return this;
		}

		public void Run()
		{
			foreach (var action in Codes)
			{
				if (action != null)
					action.Run();
			}
		}
	}
}
